package com.zitangkou.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class WebFluxSecurityConfiguration {

    @Autowired
    private WebFluxAuthenticationManager webFluxAuthenticationManager;

    @Autowired
    private WebFluxSecurityContextRepository webFluxSecurityContextRepository;

    @Autowired
    private WebFluxServerAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private WebFluxServerAccessDeniedHandler accessDeniedHandler;

    @Autowired
    private MyWebFilter webFilter;

    @Bean
    SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) {
        return http
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .authenticationManager(webFluxAuthenticationManager)
                .securityContextRepository(webFluxSecurityContextRepository)
                .authorizeExchange()
                .pathMatchers(HttpMethod.OPTIONS).permitAll()
                .pathMatchers(MyWebFilter.PATH_ARRAY).permitAll()
                .anyExchange().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler).and()
                .addFilterAt(webFilter, SecurityWebFiltersOrder.HTTP_BASIC)
                .build();
    }
}
